import { EntityManager, MikroORM } from '@mikro-orm/mysql';
import { InjectEntityManager, InjectMikroORM } from '@mikro-orm/nestjs';
import { Controller, Get, Body, Post, Query, Req } from '@nestjs/common';
import { JobTasks } from "@entities/JobTasks";
import { JobProjectSources } from "@entities/JobProjectSources";
import { JsonApiResponse } from '@utils/json.api.response';
import dayjs from 'dayjs';
import { ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
import { wrap } from '@mikro-orm/core';
import { knext } from 'knext';

@ApiTags('(管理员) 兼职-项目')
@Controller('project')
export class ProjectController {
    constructor(
        @InjectMikroORM('zp')
        private readonly orm : MikroORM,
        @InjectEntityManager('zp')
        private readonly em : EntityManager
    ){}

    @ApiOperation({
        summary:'列出用户项目-操作 (列表 L)'
    })
    @Get('list')
    async list(@Req() request){
 
        const knex = knext(this)

        const user = request['user'];

        const result = await knex
        .fromORM(JobProjectSources)
        .select(
            '*',
            knex //加入任务总数
            .fromORM(JobTasks)
            .select([knex.raw('COUNT(*)')])
            .where('source_id',knex.ref('job_project_sources.id'))
            .as('task_count'),
            knex //加入今天的一个任务
            .fromORM(JobTasks)
            .select('id')
            .where('source_id',knex.ref('job_project_sources.id'))
            .where('start_date','=',dayjs().format('YYYY-MM-DD'))
            .limit(1)
            .as('recently_task_id')
        )
        .where('creator_id',user.id)
        .take(20)
    
        return JsonApiResponse.new(result)
    }

    @ApiOperation({summary:'创建项目 (创建 C)'})
    @Post('create')
    async create(@Req() request : Request,@Body() formData)
    {
        //$formData = $request->input("formData");
        // $project = new JobProjectSource([
        //     'creator_id'=> $request->user()->id,
        //     'owner_id'=> $request->user()->id,
        //     'title' => $formData['title']
        // ]);

        const project = new JobProjectSources();
        project.creator = request['user'].id;
        project.owner = request['user'].id;
        project.title = formData.title;

        await this.em.getRepository(JobProjectSources).create(project)

        JsonApiResponse.new(wrap(project).toObject())
    }
}
